//
//  PCDApiShowCalendarView.m
//  PCDBankSix
//
//  Created by DK on 2022/3/9.
//

#import "PCDApiShowCalendarView.h"

@interface PCDApiShowCalendarView()<PCDDatePickerDelegate>
@property(nonatomic,copy) NSString *strCallBack;
@property(nonatomic,copy) NSString *failBack;

@property (nonatomic,assign) PCDDatePickerStyle pickerStyle;
@end

@implementation PCDApiShowCalendarView
- (void)handler:(id)data andContext:(PCDContext *)context ResponseCallback:(WVJBResponseCallback )responseCallback
{
    NSDictionary *dic = (NSDictionary *)data;
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateTime = [formatter stringFromDate:[NSDate date]];
    NSString *callBack = [dic objectForKey:@"success"];
    NSString *failBack = [dic objectForKey:@"fail"];
    NSString *format = [dic objectForKey:@"format"] ? [dic objectForKey:@"format"] : @"yyyy-MM-dd";
    NSString *min = [dic objectForKey:@"min"] ? [dic objectForKey:@"min"] : @"1900-01-01";
    NSString *max = [dic objectForKey:@"max"] ? [dic objectForKey:@"max"] : @"2199-12-31";
    NSString *text;
    if (![PCDUtil nilOrEmptyString:[dic objectForKey:@"text"]]) {
        if ([self isChinese:[dic objectForKey:@"text"]]) {
            text = dateTime;
        }else {
            text = [dic objectForKey:@"text"];
        }
    }else {
        text = dateTime;
    }
    self.strCallBack = callBack;
    self.failBack = failBack;
    
    self.pickerStyle = PCDDatePickerYMD;
    
    if ([format isEqual:@"HH:mm"]) {
        self.pickerStyle = PCDDatePickerHM;
    }else if ([format isEqual:@"yyyy-MM"])
    {
        self.pickerStyle = PCDDatePickerYM;
    }else if ([format isEqual:@"yyyy/MM/dd"]||[format isEqual:@"yyyy-MM-dd"]||[format isEqual:@"yyyy:MM:dd"])
    {
        self.pickerStyle = PCDDatePickerYMD;
    }
    
    
    NSDictionary *dateDict =@{@"text":text,@"format":format,@"min":min,@"max":max};
    PCDDatePickerDO *itemDO =[[PCDDatePickerDO alloc]initWithDict:dateDict];
    PCDDatePicker *datePicker =[[PCDDatePicker alloc]initWithStyle:self.pickerStyle pickerData:itemDO];
    
    datePicker.delegate = self;
    
    __weak PCDDatePicker *weakPicker = datePicker;
    __weak typeof(self) tempSelf = self;
    [datePicker.sheet setTapDismiss:^{
        [weakPicker dismissPicker];
        evaluateJavaScriptOnMainThread(tempSelf,tempSelf.failBack, [@{@"text": @""} JSONRepresentation]);
    }];
    
    [datePicker show];
    
}

-(void)datePicker:(nonnull PCDDatePicker *)customPicker result:(nullable NSString *)resultDateString
{
    NSDictionary *dict = @{@"text":resultDateString};
    evaluateJavaScriptOnMainThread(self,self.strCallBack,[dict JSONRepresentation]);
}


- (BOOL)isChinese:(NSString *)userName{
    NSString *match = @"(^[\u4e00-\u9fa5]+$)";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
    return [predicate evaluateWithObject:userName];
}

@end
